import tkinter as tk
import pyautogui

class EnhancedVisualOperationCanvas:
    """增强版可视化操作画布 - 支持操作名称和顺序显示"""
    def __init__(self, parent, width=600, height=400):
        self.canvas = tk.Canvas(parent, width=width, height=height, bg="white")
        self.canvas.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        self.operations = []
        self.selected_operation = None
        self.scale_factor = 0.5
        self.current_operation_tags = {}
        
        # 画布布局参数
        self.operation_height = 60  # 每个操作的高度
        self.margin = 20  # 边距
        self.sequence_width = 40  # 序号区域宽度
        self.content_width = width - self.sequence_width - self.margin * 2
        
        # 绑定事件
        self.canvas.bind("<Button-1>", self.on_canvas_click)
        self.canvas.bind("<B1-Motion>", self.on_canvas_drag)
        self.canvas.bind("<ButtonRelease-1>", self.on_canvas_release)
        self.canvas.bind("<Configure>", self.on_canvas_configure)
    
    def scale_coordinates(self, screen_x, screen_y):
        """将屏幕坐标缩放到画布坐标"""
        screen_width, screen_height = pyautogui.size()
        canvas_width = self.canvas.winfo_width()
        canvas_height = self.canvas.winfo_height()
        
        if canvas_width <= 1:
            canvas_width = 600
        if canvas_height <= 1:
            canvas_height = 400
            
        canvas_x = int(screen_x * canvas_width / (screen_width * self.scale_factor))
        canvas_y = int(screen_y * canvas_height / (screen_height * self.scale_factor))
        
        return canvas_x, canvas_y
        
    def on_canvas_configure(self, event):
        """画布大小变化时重绘所有操作"""
        if event.width > 10 and event.height > 10:
            # 更新画布尺寸参数
            self.content_width = max(200, event.width - self.sequence_width - self.margin * 2)  # 设置最小宽度
            self.redraw_canvas()

    def redraw_canvas(self):
        """重绘画布"""
        # 清空画布
        self.canvas.delete("all")
        
        # 重新绘制所有操作
        for i, operation in enumerate(self.operations):
            self.draw_operation(operation, i)
            
    def draw_operation(self, operation, index):
        """在画布上绘制单个操作"""
        operation_tag = f"operation_{index}"
        
        # 计算操作位置
        y_position = self.margin + index * self.operation_height
        
        # 绘制序号区域
        sequence_bg = self.canvas.create_rectangle(
            self.margin, y_position, 
            self.margin + self.sequence_width, y_position + self.operation_height - 5,
            fill="#f0f0f0", outline="#ccc", width=1,
            tags=operation_tag
        )
        
        sequence_text = self.canvas.create_text(
            self.margin + self.sequence_width // 2, y_position + self.operation_height // 2 - 2,
            text=str(index + 1), font=("Arial", 12, "bold"), fill="#333",
            tags=operation_tag
        )
        
        # 绘制操作内容区域
        content_bg = self.canvas.create_rectangle(
            self.margin + self.sequence_width, y_position,
            self.margin + self.sequence_width + self.content_width, y_position + self.operation_height - 5,
            fill=self.get_operation_color(operation["type"]), outline="#ccc", width=1,
            tags=operation_tag
        )
        
        # 绘制操作类型图标
        icon_text = self.canvas.create_text(
            self.margin + self.sequence_width + 10, y_position + 15,
            text=self.get_operation_icon(operation["type"]), font=("Arial", 10, "bold"), 
            anchor="w", fill="#fff",
            tags=operation_tag
        )
        
        # 绘制操作名称
        name_text = self.canvas.create_text(
            self.margin + self.sequence_width + 30, y_position + 15,
            text=operation["description"], font=("Arial", 10), anchor="w", fill="#fff",
            tags=operation_tag
        )
        
        # 绘制操作详细信息
        detail_text = self.canvas.create_text(
            self.margin + self.sequence_width + 10, y_position + 35,
            text=self.get_operation_details(operation), font=("Arial", 9), anchor="w", fill="#fff",
            tags=operation_tag
        )
        
        # 存储画布项目
        operation["canvas_tag"] = operation_tag
        self.current_operation_tags[operation_tag] = [
            sequence_bg, sequence_text, content_bg, icon_text, name_text, detail_text
        ]
        
        # 绘制连接线（除了第一个操作）
        if index > 0:
            prev_y = self.margin + (index - 1) * self.operation_height + self.operation_height - 5
            current_y = y_position
            
            # 绘制垂直连接线
            line = self.canvas.create_line(
                self.margin + self.sequence_width // 2, prev_y,
                self.margin + self.sequence_width // 2, current_y,
                fill="#999", width=2, arrow=tk.LAST,
                tags=f"connector_{index}"
            )
    
    def add_operation(self, operation):
        """添加操作到画布"""
        self.operations.append(operation)
        self.redraw_canvas()

    def get_operation_color(self, operation_type):
        """获取操作对应的颜色"""
        colors = {
            "click": "#e74c3c",      # 红色
            "scroll": "#3498db",     # 蓝色
            "keyboard": "#2ecc71",   # 绿色
            "wait": "#f39c12"        # 橙色
        }
        return colors.get(operation_type, "#95a5a6")  # 默认灰色
    
    def get_operation_icon(self, operation_type):
        """获取操作对应的图标"""
        icons = {
            "click": "🖱️",
            "scroll": "🔄",
            "keyboard": "⌨️",
            "wait": "⏱️"
        }
        return icons.get(operation_type, "❓")
    
    def get_operation_details(self, operation):
        """获取操作的详细信息"""
        if operation["type"] == "click":
            return f"点击位置: ({operation['x']}, {operation['y']})"
        elif operation["type"] == "scroll":
            direction = "向上" if operation["scroll_amount"] > 0 else "向下"
            return f"滚动: {abs(operation['scroll_amount'])} 像素 {direction}"
        elif operation["type"] == "keyboard":
            text_preview = operation["text"][:15] + "..." if len(operation["text"]) > 15 else operation["text"]
            return f"输入文本: {text_preview}"
        elif operation["type"] == "wait":
            return f"等待: {operation['wait_time']} 秒"
        return "未知操作"
    
    def on_canvas_click(self, event):
        """画布点击事件"""
        items = self.canvas.find_overlapping(event.x-5, event.y-5, event.x+5, event.y+5)
        
        if items:
            for item in items:
                tags = self.canvas.gettags(item)
                if tags:
                    for tag in tags:
                        if tag.startswith("operation_"):
                            for operation in self.operations:
                                if "canvas_tag" in operation and operation["canvas_tag"] == tag:
                                    self.select_operation(operation)
                                    return
        
        self.deselect_operation()
    
    def on_canvas_drag(self, event):
        """画布拖拽事件"""
        # 在顺序布局中，拖拽主要用于调整操作顺序
        if self.selected_operation:
            # 计算新的位置索引
            new_index = max(0, min(len(self.operations) - 1, 
                                 (event.y - self.margin) // self.operation_height))
            
            current_index = self.operations.index(self.selected_operation)
            if new_index != current_index:
                # 移动操作到新位置
                self.operations.pop(current_index)
                self.operations.insert(new_index, self.selected_operation)
                self.redraw_canvas()
    
    def on_canvas_release(self, event):
        """画布鼠标释放事件"""
        pass
    
    def select_operation(self, operation):
        """选择操作"""
        if self.selected_operation:
            self.deselect_operation()
            
        self.selected_operation = operation
        self.highlight_operation(operation)
        
        if hasattr(self, 'on_operation_select_callback'):
            index = self.operations.index(operation)
            self.on_operation_select_callback(index)
    
    def deselect_operation(self):
        """取消选择操作"""
        if self.selected_operation:
            # 取消高亮之前选中的操作
            self.unhighlight_operation(self.selected_operation)
            self.selected_operation = None
    
    def highlight_operation(self, operation):
        """高亮显示操作"""
        if "canvas_tag" in operation and operation["canvas_tag"] in self.current_operation_tags:
            items = self.current_operation_tags[operation["canvas_tag"]]
            for item in items:
                try:
                    # 高亮内容区域
                    if self.canvas.type(item) == "rectangle":
                        self.canvas.itemconfig(item, outline="#f39c12", width=3)
                except tk.TclError:
                    pass
    
    def unhighlight_operation(self, operation):
        """取消高亮操作"""
        if "canvas_tag" in operation and operation["canvas_tag"] in self.current_operation_tags:
            items = self.current_operation_tags[operation["canvas_tag"]]
            for item in items:
                try:
                    if self.canvas.type(item) == "rectangle":
                        # 恢复原始颜色
                        if item == self.current_operation_tags[operation["canvas_tag"]][2]:  # 内容区域
                            self.canvas.itemconfig(item, outline="#ccc", width=1)
                        else:  # 序号区域
                            self.canvas.itemconfig(item, outline="#ccc", width=1)
                except tk.TclError:
                    pass
    
    def redraw_canvas(self):
        """重绘画布"""
        selected_operation = self.selected_operation
        
        self.canvas.delete("all")
        self.current_operation_tags = {}
        
        # 绘制标题
        self.canvas.create_text(
            self.margin, 30, text="执行序列", 
            font=("Arial", 12, "bold"), anchor="w", fill="#333"
        )
        
        # 绘制所有操作
        for i, operation in enumerate(self.operations):
            self.draw_operation(operation, i)
        
        # 恢复选择状态
        if selected_operation:
            self.selected_operation = selected_operation
            self.highlight_operation(selected_operation)
    
    def clear_canvas(self):
        """清空画布"""
        self.canvas.delete("all")
        self.operations = []
        self.selected_operation = None
        self.current_operation_tags = {}
    
    def remove_operation(self, operation):
        """移除指定操作"""
        if operation in self.operations:
            self.operations.remove(operation)
            self.redraw_canvas()